package net.technics;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

import net.hibernate.HibernateUtil;
import net.models.Application;
import net.models.Echantillons;
import net.models.Medicaments;
import net.models.Praticiens;
import net.models.Presentations;
import net.models.RapportsVisites;
import net.models.Users;

import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.list.IObservableList;
import org.eclipse.core.databinding.observable.map.IObservableMap;
import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.property.Properties;
import org.eclipse.core.internal.databinding.property.set.SimplePropertyObservableSet;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
import org.eclipse.jface.databinding.viewers.ObservableMapLabelProvider;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.databinding.viewers.ViewerProperties;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
import org.hibernate.Transaction;

public class CompteRenduEditer {
	private DataBindingContext			m_bindingContext;

	protected Shell						shlBackOfficeManagement;
	private Text						textBilanCR;
	private Text						txtAjouterUnCompterendu;
	private List<Praticiens>			praticiens		= new ArrayList<>();
	private List<Users>					users			= new ArrayList<>();
	private List<RapportsVisites>		rapportsVisites	= new ArrayList<>();
	private List<Echantillons>			echantillons	= new ArrayList<>();
	private List<Medicaments>			medicaments		= new ArrayList<>();
	private List<Presentations>			presentations	= new ArrayList<>();
	private Users						user			= new Users();
	private RapportsVisites				rapportsVisite	= new RapportsVisites();
	private ArrayList<Presentations>	presentationses;
	private ComboViewer					cmbViewerUserCR;
	private ComboViewer					cmbViewerCR;
	private CLabel						lblBilan;
	private DateTime					dateTime;
	private CLabel						lblDateDeLa;
	private CLabel						lblPraticienVisit;
	private CLabel						lblerMdicamentPrsent;
	private CLabel						lblndMdicamentPrsent;
	private CLabel						lblerchantillonPrsent;
	private CLabel						lblndchantillonDistribu;
	private Spinner						spinner;
	private Spinner						spinner_1;
	private ComboViewer					cmbViewerMed1;
	private Combo						cmbMed1;
	private ComboViewer					cmbViewerMed2;
	private Combo						cmbMed2;
	private ComboViewer					cmbViewerEchan1;
	private Combo						cmbEchan1;
	private ComboViewer					cmbViewerEchan2;
	private Combo						cmbEchan2;
	private ComboViewer					cmbViewerPratCR;
	private Combo						cmbPratCR;
	private RapportsVisites				rv;
	private Presentations				presentation1;
	private Presentations				presentation2;
	private Echantillons				echantillon1;
	private Echantillons				echantillon2;
	private Medicaments					medicament2;
	private ArrayList<Echantillons>		echantillonses;

	/**
	 * Launch the application.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Display display = Display.getDefault();
		Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
			public void run() {
				try {
					CompteRenduEditer window = new CompteRenduEditer();
					window.open();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Open the window.
	 */
	public void open() {
		praticiens = Application.getPraticiens();
		users = Application.getUsers();
		rapportsVisites = Application.getRapportsVisites();
		echantillons = Application.getEchantillons();
		medicaments = Application.getMeds();
		presentations = Application.getPresentations();
		Display display = Display.getDefault();
		createContents();
		shlBackOfficeManagement.open();
		shlBackOfficeManagement.layout();
		while (!shlBackOfficeManagement.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shlBackOfficeManagement = new Shell();
		shlBackOfficeManagement.setSize(518, 650);
		shlBackOfficeManagement.setText("Back Office Management");

		Group grpCompterendu = new Group(shlBackOfficeManagement, SWT.NONE);
		grpCompterendu.setText("Compte-rendu");
		grpCompterendu.setBounds(10, 139, 482, 404);

		dateTime = new DateTime(grpCompterendu, SWT.BORDER);
		dateTime.setBounds(10, 53, 183, 24);

		textBilanCR = new Text(grpCompterendu, SWT.BORDER);
		textBilanCR.setBounds(10, 110, 465, 57);

		lblBilan = new CLabel(grpCompterendu, SWT.NONE);
		lblBilan.setBounds(10, 83, 61, 21);
		lblBilan.setText("Bilan");

		lblDateDeLa = new CLabel(grpCompterendu, SWT.NONE);
		lblDateDeLa.setText("Date de la visite");
		lblDateDeLa.setBounds(10, 26, 93, 21);

		lblPraticienVisit = new CLabel(grpCompterendu, SWT.NONE);
		lblPraticienVisit.setText("Praticien visité");
		lblPraticienVisit.setBounds(10, 173, 103, 21);

		lblerMdicamentPrsent = new CLabel(grpCompterendu, SWT.NONE);
		lblerMdicamentPrsent.setBounds(10, 229, 140, 21);
		lblerMdicamentPrsent.setText("1er médicament présenté");

		lblndMdicamentPrsent = new CLabel(grpCompterendu, SWT.NONE);
		lblndMdicamentPrsent.setText("2nd médicament présenté");
		lblndMdicamentPrsent.setBounds(236, 229, 144, 21);

		lblerchantillonPrsent = new CLabel(grpCompterendu, SWT.NONE);
		lblerchantillonPrsent.setText("1er échantillon distribué");
		lblerchantillonPrsent.setBounds(10, 285, 140, 21);

		lblndchantillonDistribu = new CLabel(grpCompterendu, SWT.NONE);
		lblndchantillonDistribu.setText("2nd échantillon distribué");
		lblndchantillonDistribu.setBounds(10, 342, 140, 21);

		spinner = new Spinner(grpCompterendu, SWT.BORDER);
		spinner.setBounds(236, 314, 183, 22);

		spinner_1 = new Spinner(grpCompterendu, SWT.BORDER);
		spinner_1.setBounds(236, 371, 183, 22);

		cmbViewerMed1 = new ComboViewer(grpCompterendu, SWT.NONE);
		cmbMed1 = cmbViewerMed1.getCombo();
		cmbMed1.setBounds(10, 256, 183, 23);

		cmbViewerMed2 = new ComboViewer(grpCompterendu, SWT.NONE);
		cmbMed2 = cmbViewerMed2.getCombo();
		cmbMed2.setBounds(236, 256, 183, 23);

		cmbViewerEchan1 = new ComboViewer(grpCompterendu, SWT.NONE);
		cmbEchan1 = cmbViewerEchan1.getCombo();
		cmbEchan1.setBounds(10, 312, 183, 23);

		cmbViewerEchan2 = new ComboViewer(grpCompterendu, SWT.NONE);
		cmbEchan2 = cmbViewerEchan2.getCombo();
		cmbEchan2.setBounds(10, 369, 183, 23);

		cmbViewerPratCR = new ComboViewer(grpCompterendu, SWT.NONE);
		cmbPratCR = cmbViewerPratCR.getCombo();
		cmbPratCR.setBounds(10, 200, 183, 23);

		Composite composite = new Composite(shlBackOfficeManagement, SWT.NONE);
		composite.setBackground(SWTResourceManager.getColor(102, 153, 0));
		composite.setBounds(0, 0, 500, 48);

		txtAjouterUnCompterendu = new Text(composite, SWT.NONE);
		txtAjouterUnCompterendu.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.BOLD));
		txtAjouterUnCompterendu.setForeground(SWTResourceManager.getColor(255, 255, 255));
		txtAjouterUnCompterendu.setBackground(SWTResourceManager.getColor(102, 153, 0));
		txtAjouterUnCompterendu.setText("Consulter un compte-rendu");
		txtAjouterUnCompterendu.setBounds(10, 10, 223, 21);

		Composite composite_1 = new Composite(shlBackOfficeManagement, SWT.NONE);
		composite_1.setBounds(241, 549, 251, 52);

		Button button = new Button(composite_1, SWT.NONE);
		button.setText("Annuler");
		button.setBounds(131, 10, 90, 30);

		Group grpCompterenduModifier = new Group(shlBackOfficeManagement, SWT.NONE);
		grpCompterenduModifier.setText("Compte-rendu à modifier");
		grpCompterenduModifier.setBounds(10, 54, 482, 82);

		cmbViewerCR = new ComboViewer(grpCompterenduModifier, SWT.NONE);
		Combo cmbCR = cmbViewerCR.getCombo();
		cmbCR.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				IStructuredSelection sel = (IStructuredSelection) (cmbViewerCR.getSelection());
				rapportsVisite = (RapportsVisites) (sel.iterator().next());
				presentationses = new ArrayList<>(rapportsVisite.getPresentationses());
				echantillonses = new ArrayList<>(rapportsVisite.getEchantillonses());
				textBilanCR.setText(rapportsVisite.getBilan());
				cmbViewerPratCR.setSelection(new StructuredSelection(rapportsVisite.getPraticiens()));

				if (presentationses.size() == 1) {
					for (Medicaments medic : medicaments) {
						if (presentationses.get(0).getMedicamentId().equals(medic.getId())) {
							cmbViewerMed1.setSelection(new StructuredSelection(medic));
						}
					}
				} else {
					for (Medicaments medic : medicaments) {
						if (presentationses.get(0).getMedicamentId().equals(medic.getId())) {
							cmbViewerMed1.setSelection(new StructuredSelection(medic));
						}
						if (presentationses.get(1).getMedicamentId().equals(medic.getId())) {
							cmbViewerMed2.setSelection(new StructuredSelection(medic));
						}
					}
				}

				if (echantillonses.size() == 1) {
					for (Medicaments medic : medicaments) {
						if (echantillonses.get(0).getMedicaments().equals(medic)) {
							cmbViewerEchan1.setSelection(new StructuredSelection(medic));
							spinner.setSelection(medic.getPrixEchantillon());
						}
					}
				} else {
					for (Medicaments medic : medicaments) {
						if (echantillonses.get(0).getMedicaments().equals(medic)) {
							cmbViewerEchan1.setSelection(new StructuredSelection(medic));
							spinner.setSelection(medic.getPrixEchantillon());
						}
						if (echantillonses.get(1).getMedicaments().equals(medic)) {
							cmbViewerEchan2.setSelection(new StructuredSelection(medic));
							spinner_1.setSelection(medic.getPrixEchantillon());
						}
					}
				}
			}
		});
		cmbCR.setBounds(199, 31, 183, 23);

		cmbViewerUserCR = new ComboViewer(grpCompterenduModifier, SWT.NONE);
		Combo cmbUserCR = cmbViewerUserCR.getCombo();
		cmbUserCR.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				((SimplePropertyObservableSet) cmbViewerCR.getInput()).clear();
				IStructuredSelection sel = (IStructuredSelection) (cmbViewerUserCR.getSelection());
				user = (Users) (sel.iterator().next());
				for (RapportsVisites rv : user.getRapportsVisites()) {
					try {
						((SimplePropertyObservableSet) cmbViewerCR.getInput()).add(rv);
					} catch (NoSuchElementException exception) {
						System.out.println("Input sans élément");
					}
				}
			}
		});
		cmbUserCR.setBounds(10, 31, 183, 23);

		Button button_1 = new Button(composite_1, SWT.NONE);
		button_1.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseUp(MouseEvent e) {
				org.hibernate.Session session = (org.hibernate.Session) HibernateUtil.getSession();
				Transaction trans = session.beginTransaction();
				IStructuredSelection selMedicament1 = (IStructuredSelection) (cmbViewerMed1.getSelection());
				Medicaments medicament1 = (Medicaments) (selMedicament1.iterator().next());
				IStructuredSelection selMedicament2 = (IStructuredSelection) (cmbViewerMed2.getSelection());
				Medicaments medicament2 = (Medicaments) (selMedicament2.iterator().next());
				IStructuredSelection selEchant1 = (IStructuredSelection) (cmbViewerEchan1.getSelection());
				Medicaments medicament3 = (Medicaments) (selEchant1.iterator().next());
				IStructuredSelection selEchant2 = (IStructuredSelection) (cmbViewerEchan2.getSelection());
				Medicaments medicament4 = (Medicaments) (selEchant2.iterator().next());

				if (presentationses.size() == 1 && !medicament2.getName().equals(null)) {
					presentation2 = new Presentations(rapportsVisite, medicament2.getId());
					session.persist(presentation2);
				} else if (presentationses.size() == 2) {
					if (!presentationses.get(0).getMedicamentId().equals(medicament1.getId())) {
						session.delete(presentationses.get(0));
						presentation1 = new Presentations(rapportsVisite, medicament1.getId());
						session.persist(presentation1);
					} else if (!presentationses.get(1).getMedicamentId().equals(medicament2.getId())) {
						session.delete(presentationses.get(1));
						presentation2 = new Presentations(rapportsVisite, medicament2.getId());
						session.persist(presentation2);
					}
				}

				// if (echantillonses.size() == 1 &&
				// !medicament4.getName().equals(null)) {
				// echantillon2 = new Echantillons(rapportsVisite, medicament4);
				// session.persist(echantillon2);
				// } else if (echantillonses.size() == 2) {
				// if
				// (!echantillonses.get(0).getMedicaments().equals(medicament3))
				// {
				// session.delete(echantillonses.get(0));
				// echantillon1 = new Echantillons(rapportsVisite, medicament3);
				// session.persist(echantillon1);
				// } else if
				// (!echantillonses.get(2).getMedicaments().equals(medicament4))
				// {
				// session.delete(echantillonses.get(1));
				// echantillon2 = new Echantillons(rapportsVisite, medicament4);
				// session.persist(echantillon2);
				// }
				// }

				IStructuredSelection selRapportVisite = (IStructuredSelection) (cmbViewerCR.getSelection());
				RapportsVisites rapportsVisite = (RapportsVisites) (selRapportVisite.iterator().next());
				IStructuredSelection selUser = (IStructuredSelection) (cmbViewerUserCR.getSelection());
				Users user = (Users) (selUser.iterator().next());
				IStructuredSelection selPrat = (IStructuredSelection) (cmbViewerPratCR.getSelection());
				Praticiens praticien = (Praticiens) (selPrat.iterator().next());
				rv = new RapportsVisites(rapportsVisite.getId(), user, textBilanCR.getText(), praticien);
				session.update(rv);

				trans.commit();
				session.close();
			}
		});
		button_1.setText("Valider");
		button_1.setBounds(35, 10, 90, 30);

		m_bindingContext = initDataBindings();

	}

	protected DataBindingContext initDataBindings() {
		DataBindingContext bindingContext = new DataBindingContext();
		//
		ObservableListContentProvider listContentProvider = new ObservableListContentProvider();
		IObservableMap[] observeMaps = BeansObservables.observeMaps(listContentProvider.getKnownElements(), Users.class, new String[] { "name", "prenom" });
		cmbViewerUserCR.setLabelProvider(new ObservableMapLabelProvider(observeMaps));
		cmbViewerUserCR.setContentProvider(listContentProvider);
		//
		IObservableList selfList = Properties.selfList(Users.class).observe(users);
		cmbViewerUserCR.setInput(selfList);
		//
		ObservableSetContentProvider setContentProvider = new ObservableSetContentProvider();
		IObservableMap observeMap = BeansObservables.observeMap(setContentProvider.getKnownElements(), RapportsVisites.class, "date");
		cmbViewerCR.setLabelProvider(new ObservableMapLabelProvider(observeMap));
		cmbViewerCR.setContentProvider(setContentProvider);
		//
		IObservableSet selfSet = Properties.selfSet(RapportsVisites.class).observe(user.getRapportsVisites());
		cmbViewerCR.setInput(selfSet);
		//
		ObservableListContentProvider listContentProvider_1 = new ObservableListContentProvider();
		IObservableMap[] observeMaps_1 = BeansObservables.observeMaps(listContentProvider_1.getKnownElements(), Praticiens.class, new String[] { "name", "prenom" });
		cmbViewerPratCR.setLabelProvider(new ObservableMapLabelProvider(observeMaps_1));
		cmbViewerPratCR.setContentProvider(listContentProvider_1);
		//
		IObservableList selfList_1 = Properties.selfList(Praticiens.class).observe(praticiens);
		cmbViewerPratCR.setInput(selfList_1);
		//
		ObservableListContentProvider listContentProvider_2 = new ObservableListContentProvider();
		IObservableMap observeMap_1 = BeansObservables.observeMap(listContentProvider_2.getKnownElements(), Medicaments.class, "name");
		cmbViewerMed1.setLabelProvider(new ObservableMapLabelProvider(observeMap_1));
		cmbViewerMed1.setContentProvider(listContentProvider_2);
		//
		IObservableList selfList_2 = Properties.selfList(Medicaments.class).observe(medicaments);
		cmbViewerMed1.setInput(selfList_2);
		//
		ObservableListContentProvider listContentProvider_3 = new ObservableListContentProvider();
		IObservableMap observeMap_2 = BeansObservables.observeMap(listContentProvider_3.getKnownElements(), Medicaments.class, "name");
		cmbViewerMed2.setLabelProvider(new ObservableMapLabelProvider(observeMap_2));
		cmbViewerMed2.setContentProvider(listContentProvider_3);
		//
		cmbViewerMed2.setInput(selfList_2);
		//
		IObservableValue observeSingleSelectionCmbViewerPratCR = ViewerProperties.singleSelection().observe(cmbViewerPratCR);
		IObservableValue nameRapportsVisitegetPraticiensObserveValue = BeanProperties.value("name").observe(rapportsVisite.getPraticiens());
		bindingContext.bindValue(observeSingleSelectionCmbViewerPratCR, nameRapportsVisitegetPraticiensObserveValue, null, null);
		//
		ObservableListContentProvider listContentProvider_4 = new ObservableListContentProvider();
		IObservableMap observeMap_3 = BeansObservables.observeMap(listContentProvider_4.getKnownElements(), Medicaments.class, "name");
		cmbViewerEchan1.setLabelProvider(new ObservableMapLabelProvider(observeMap_3));
		cmbViewerEchan1.setContentProvider(listContentProvider_4);
		//
		cmbViewerEchan1.setInput(selfList_2);
		//
		ObservableListContentProvider listContentProvider_5 = new ObservableListContentProvider();
		IObservableMap observeMap_4 = BeansObservables.observeMap(listContentProvider_5.getKnownElements(), Medicaments.class, "name");
		cmbViewerEchan2.setLabelProvider(new ObservableMapLabelProvider(observeMap_4));
		cmbViewerEchan2.setContentProvider(listContentProvider_5);
		//
		cmbViewerEchan2.setInput(selfList_2);
		//
		return bindingContext;
	}
}
